package cn.le.io;

import nu.xom.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static cn.le.io.Person.format;

/**
 * 对象序列化是Java的解决方案，具有跨语言的特点，为了让对种语言使用，
 * 一个更具相互操作性的解决方案是将数据转换为xml格式
 *
 * 将Person对象转换成xml
 */
public class XMLDemo {

    public static void main(String[] args) throws IOException, ParsingException {
        List<Person> personList = Arrays.asList(
                new Person("Dr Bunsen","Honeydew"),
                new Person("Gonzo","the great"),
                new Person("phillip","fry")
        );
        //节点
        Element root = new Element("people");
        for (Person p:personList)
        {
            root.appendChild(p.getXML());
        }
        Document doc = new Document(root);
        format(System.out,doc);

        format(new BufferedOutputStream(new FileOutputStream("/home/le/People.xml")),doc);

        //恢复成对象
        List<Person> persons = new ArrayList<>();
        Document document = new Builder().build("/home/le/People.xml");
        Elements elements =  document.getRootElement().getChildElements();
        for (int i = 0; i < elements.size(); i++) {
            Element element = elements.get(i);
            Person person = new Person(element.getFirstChildElement("first").getValue(),
                    element.getFirstChildElement("last").getValue());
            persons.add(person);
        }
        System.out.println(persons);
    }

}
class Person{

    private String first,last;
    public Person(String first,String last)
    {
        this.first = first;
        this.last = last;
    }
    public Person(Element person)
    {
        first = person.getFirstChildElement("first").getValue();
        last = person.getFirstChildElement("last").getValue();
    }

    public Element getXML()
    {
        Element person = new Element("person");

        Element firstName = new Element("first");
        firstName.appendChild(first);

        Element lastName = new Element(("last"));
        lastName.appendChild(last);

        person.appendChild(firstName);
        person.appendChild(lastName);

        return person;
    }

    public static void format(OutputStream os, Document doc) throws IOException {
        Serializer serializer = new Serializer(os,"iso-8859-1");
        serializer.setIndent(4);
        serializer.setMaxLength(60);
        serializer.write(doc);
        serializer.flush();
    }

    @Override
    public String toString() {
        return "Person{" +
                "first='" + first + '\'' +
                ", last='" + last + '\'' +
                '}';
    }
}